package com.neusoft.elmboot.config;

import com.neusoft.elmboot.po.User;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();

        if(UrlFilterList.list.contains(requestURI) ||"OPTIONS".equalsIgnoreCase(((HttpServletRequest) servletRequest).getMethod())) {
            filterChain.doFilter(request, response);
            return;
        }
        User user= TokenConfig.getLoginUser(request);
        if(user == null){
            String msg = "认证失败，无法访问系统资源";
            renderString(response, msg);
        }else {
            filterChain.doFilter(request, response);
        }
    }
    public static String renderString(HttpServletResponse response, String string)
    {
        try
        {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(string);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void destroy() {
        // 销毁资源操作
    }
}
